import {defineStore} from 'pinia'
import areaCalculator from '@/utils/areaCalculator'
import { useRoomStore } from '@/stores/room'
export const useGameStore = defineStore('game',{
    state:() =>({
        canvas:null,
        ctx:null,
        myColor:'#000',
        brushSize:12,
        areas:{},
        timeLeft:60,
        gameTimer: null
    }),
    actions:{
        initCanvas(canvasEl) {
            this.canvas=canvasEl
            this.ctx = canvasEl.getContext('2d')
            this.ctx.lineCap = 'round'
            
            // 设置画布背景为白色
            this.ctx.fillStyle = '#FFFFFF'
            this.ctx.fillRect(0, 0, canvasEl.width, canvasEl.height)
            
            console.log(`画布初始化完成: ${canvasEl.width}x${canvasEl.height}`)
            
            // 初始化画布时同步当前玩家颜色
            this.syncPlayerColor()
        },
        drawPixel(x,y) {
            if (!this.ctx) {
                console.warn('画布上下文未初始化，无法绘制')
                return
            }
            
            // 确保使用当前设置的颜色
            this.ctx.fillStyle = this.myColor
            console.log(`绘制像素: 位置(${x},${y}), 颜色: ${this.myColor}`)
            
            // 使用矩形绘制，确保覆盖指定区域
            this.ctx.fillRect(x, y, this.brushSize, this.brushSize)
        },
        updateAreas() {
            if (this.canvas) {
                this.areas = areaCalculator(this.canvas)
                
                // 更新当前玩家的面积统计
                const roomStore = useRoomStore()
                const currentPlayer = roomStore.players.find(p => p.isCurrent)
                if (currentPlayer) {
                    // 找到当前玩家颜色的面积
                    const currentColor = currentPlayer.color
                    if (currentColor && this.areas[currentColor]) {
                        currentPlayer.area = this.areas[currentColor]
                        console.log(`更新玩家面积: ${currentPlayer.name} = ${currentPlayer.area}`)
                    }
                }
            }
        },
        setTimeLeft(t) {
            this.timeLeft =t
        },
        
        // 同步当前玩家颜色
        syncPlayerColor() {
            const roomStore = useRoomStore()
            const currentPlayer = roomStore.players.find(p => p.isCurrent)
            if (currentPlayer && currentPlayer.color) {
                console.log(`同步玩家颜色: ${currentPlayer.color}`)
                this.myColor = currentPlayer.color
            }
        },
        
        // 设置玩家颜色
        setPlayerColor(color) {
            console.log(`设置游戏存储颜色: ${color}`)
            this.myColor = color
            // 不再在这里直接更新房间存储中的玩家颜色，由roomStore的setPlayerColor方法统一处理
        },
        
        // 开始游戏倒计时
        startGameTimer() {
            // 清除可能存在的旧计时器
            this.stopGameTimer()
            
            // 重置时间为60秒（1分钟）
            this.timeLeft = 60
            
            // 同步玩家颜色
            this.syncPlayerColor()
            
            // 设置新的倒计时器
            this.gameTimer = setInterval(() => {
                this.timeLeft--
                
                // 每秒钟更新一次面积数据（游戏进行中）
                if (this.canvas && this.timeLeft > 0) {
                    this.updateAreas()
                }
                
                // 倒计时结束
                if (this.timeLeft <= 0) {
                    this.stopGameTimer()
                    this.endGame()
                }
            }, 1000)
        },
        
        // 停止游戏倒计时
        stopGameTimer() {
            if (this.gameTimer) {
                clearInterval(this.gameTimer)
                this.gameTimer = null
            }
        },
        
        // 结束游戏
        endGame() {
            const roomStore = useRoomStore()
            roomStore.endGame()
            
            // 计算最终得分并更新玩家状态
            this.calculateFinalScores()
        },
        
        // 计算最终得分
        calculateFinalScores() {
            // 这里可以实现基于涂色区域计算最终得分的逻辑
            // 当前简单实现：将玩家涂色的像素区域作为得分
            
            const roomStore = useRoomStore()
            const currentPlayer = roomStore.players.find(p => p.isCurrent)
            
            if (currentPlayer) {
                // 更新得分（这里使用一个模拟值，实际应该基于canvas计算）
                currentPlayer.score = Object.values(this.areas).reduce((total, area) => total + area, 0)
            }
        }
    },
    
    // 销毁时清除计时器
    unmounted() {
        this.stopGameTimer()
    }
})